<!-- 位置缓存功能测试组件 -->
<template>
  <view class="min-h-screen bg-gray-50 p-6">
    <!-- 页面标题 -->
    <view class="mb-8">
      <text class="text-[36rpx] font-bold text-gray-900 text-center">位置缓存功能测试</text>
    </view>

    <!-- 功能说明 -->
    <view class="bg-blue-50 border border-blue-200 rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-blue-900 mb-4">缓存功能说明</view>
      <view class="space-y-3 text-[24rpx] text-blue-800">
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            1
          </view>
          <text class="flex-1">Store初始化时自动从缓存加载位置信息</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            2
          </view>
          <text class="flex-1">获取位置后自动保存到缓存</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            3
          </view>
          <text class="flex-1">手动选择位置后保存到缓存</text>
        </view>
        <view class="flex items-start">
          <view class="w-[24rpx] h-[24rpx] bg-blue-500 text-white rounded-full flex items-center justify-center text-[16rpx] font-bold mr-3 mt-1 flex-shrink-0">
            4
          </view>
          <text class="flex-1">提供手动缓存操作方法</text>
        </view>
      </view>
    </view>

    <!-- 当前位置信息 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">当前位置信息</view>
      <view class="space-y-3 text-[24rpx] text-gray-700">
        <view class="flex justify-between">
          <text>省份：</text>
          <text class="font-medium text-blue-600">{{ locationObj.address_component?.province || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>城市：</text>
          <text class="font-medium text-blue-600">{{ locationObj.address_component?.city || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>详细地址：</text>
          <text class="font-medium text-blue-600">{{ locationObj.address || '未获取' }}</text>
        </view>
        <view class="flex justify-between">
          <text>经纬度：</text>
          <text class="font-medium text-blue-600">
            {{ locationObj.location?.lat && locationObj.location?.lng 
              ? `${locationObj.location.lat}, ${locationObj.location.lng}` 
              : '未获取' }}
          </text>
        </view>
      </view>
    </view>

    <!-- 缓存操作 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">缓存操作</view>
      
      <view class="grid grid-cols-2 gap-4 mb-6">
        <nut-button
          type="primary"
          size="large"
          @click="loadFromCache"
        >
          从缓存加载
        </nut-button>
        
        <nut-button
          type="success"
          size="large"
          @click="saveToCache"
        >
          保存到缓存
        </nut-button>
      </view>
      
      <view class="grid grid-cols-2 gap-4">
        <nut-button
          type="warning"
          size="large"
          @click="clearCache"
        >
          清空缓存
        </nut-button>
        
        <nut-button
          type="info"
          size="large"
          @click="showCacheInfo"
        >
          查看缓存
        </nut-button>
      </view>
    </view>

    <!-- 位置选择 -->
    <view class="bg-white rounded-2xl p-6 shadow-sm mb-6">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">位置选择</view>
      
      <nut-button
        type="primary"
        size="large"
        @click="showRegionPicker = true"
        class="w-full mb-4"
      >
        手动选择位置
      </nut-button>
      
      <nut-button
        type="default"
        size="large"
        @click="getCurrentLocation"
        class="w-full"
      >
        获取当前位置
      </nut-button>
    </view>

    <!-- 操作历史 -->
    <view v-if="operationHistory.length > 0" class="bg-white rounded-2xl p-6 shadow-sm">
      <view class="text-[32rpx] font-semibold text-gray-900 mb-4">操作历史</view>
      <view class="space-y-3">
        <view 
          v-for="(record, index) in operationHistory" 
          :key="index"
          class="flex items-center justify-between p-3 bg-gray-50 rounded-lg"
        >
          <view class="flex items-center">
            <IconFont name="check-circle" class="text-green-600 mr-2" size="24rpx" />
            <text class="text-[24rpx] text-gray-800">{{ record.operation }}</text>
          </view>
          <text class="text-[22rpx] text-gray-500">{{ record.timestamp }}</text>
        </view>
      </view>
    </view>

    <!-- 位置选择弹窗 -->
    <RegionPickerModal
      v-model:visible="showRegionPicker"
      mode="city"
      title="选择位置"
      @confirm="handleRegionConfirm"
      @cancel="handleRegionCancel"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'
import Taro from '@tarojs/taro'
import { useUserStore } from '@/store/user'
import { storeToRefs } from 'pinia'
import RegionPickerModal from './RegionPickerModal.vue'

/**
 * 操作历史类型
 */
interface OperationRecord {
  operation: string
  timestamp: string
}

// 使用store
const userStore = useUserStore()
const { locationObj } = storeToRefs(userStore)

// 响应式数据
const showRegionPicker = ref(false)
const operationHistory = ref<OperationRecord[]>([])

/**
 * 添加操作记录
 */
const addOperationRecord = (operation: string) => {
  operationHistory.value.unshift({
    operation,
    timestamp: new Date().toLocaleTimeString()
  })
  
  // 只保留最近10条记录
  if (operationHistory.value.length > 10) {
    operationHistory.value = operationHistory.value.slice(0, 10)
  }
}

/**
 * 从缓存加载位置信息
 */
const loadFromCache = () => {
  userStore.loadLocationFromCache()
  addOperationRecord('从缓存加载位置信息')
  
  Taro.showToast({
    title: '已从缓存加载位置信息',
    icon: 'success'
  })
}

/**
 * 保存位置信息到缓存
 */
const saveToCache = () => {
  userStore.saveLocationToCache()
  addOperationRecord('保存位置信息到缓存')
  
  Taro.showToast({
    title: '位置信息已保存到缓存',
    icon: 'success'
  })
}

/**
 * 清空缓存
 */
const clearCache = () => {
  try {
    Taro.removeStorageSync('locationObj')
    addOperationRecord('清空位置缓存')
    
    Taro.showToast({
      title: '缓存已清空',
      icon: 'success'
    })
  } catch (error) {
    console.error('清空缓存失败:', error)
    Taro.showToast({
      title: '清空缓存失败',
      icon: 'error'
    })
  }
}

/**
 * 查看缓存信息
 */
const showCacheInfo = () => {
  try {
    const cachedLocation = Taro.getStorageSync('locationObj')
    if (cachedLocation) {
      addOperationRecord('查看缓存信息')
      console.log('缓存的位置信息:', cachedLocation)
      
      Taro.showModal({
        title: '缓存信息',
        content: `省份: ${cachedLocation.address_component?.province || '无'}\n城市: ${cachedLocation.address_component?.city || '无'}\n地址: ${cachedLocation.address || '无'}`,
        showCancel: false
      })
    } else {
      Taro.showToast({
        title: '暂无缓存数据',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('查看缓存失败:', error)
    Taro.showToast({
      title: '查看缓存失败',
      icon: 'error'
    })
  }
}

/**
 * 获取当前位置
 */
const getCurrentLocation = () => {
  userStore.getLocation()
  addOperationRecord('获取当前位置')
  
  Taro.showToast({
    title: '正在获取位置...',
    icon: 'loading',
    duration: 2000
  })
}

/**
 * 处理区域选择确认
 */
const handleRegionConfirm = (result: any) => {
  if (result.province && result.city) {
    // 更新locationObj
    locationObj.value = {
      ...locationObj.value,
      address_component: {
        ...locationObj.value.address_component,
        province: result.province.name,
        city: result.city.name
      }
    }
    
    // 保存到缓存
    userStore.saveLocationToCache()
    
    // 关闭弹窗
    showRegionPicker.value = false
    
    addOperationRecord(`手动选择位置: ${result.province.name} ${result.city.name}`)
    
    Taro.showToast({
      title: `已选择：${result.province.name} ${result.city.name}`,
      icon: 'success'
    })
  }
}

/**
 * 处理区域选择取消
 */
const handleRegionCancel = () => {
  showRegionPicker.value = false
  addOperationRecord('取消位置选择')
  
  Taro.showToast({
    title: '已取消选择',
    icon: 'none'
  })
}
</script>
